package org.funtester.performance.books.chapter03.section7;

import org.funtester.performance.books.chapter03.common.ThreadTool;
import org.funtester.performance.books.chapter03.section3.ThreadTask;
import org.funtester.performance.books.chapter03.section4.TaskExecutor;

import java.util.ArrayList;
import java.util.List;

/**
 * 超市收银台性能测试用例
 */
public class SupermarketCheckoutCase {

    public static void main(String[] args) throws InterruptedException {
        int total = 1000;
        List<ThreadTask> tasks = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            SupermarketCheckoutTaskFirst supermarketCheckoutTask = new SupermarketCheckoutTaskFirst(total);
            tasks.add(supermarketCheckoutTask);
        }
        TaskExecutor taskExecutor = new TaskExecutor(tasks, "超市收银台性能测试用例", 120);
        Thread thread = new Thread() {
            @Override
            public void run() {
                while (taskExecutor.realTimeKey) {
                    ThreadTool.sleep(1000);// 休眠1秒
                    long sumCost = TaskExecutor.realTimeCostTime.sumThenReset();// 重置总耗时
                    long sumTimes = TaskExecutor.realTimeCostTimes.sumThenReset();// 重置总次数
                    System.out.println(String.format("实时统计TPS: %d, 平均耗时: %d", sumTimes, sumTimes == 0 ? 0 : sumCost / sumTimes));
                    long price = SupermarketCheckoutTaskFirst.priceCostTime.getAndSet(0);
                    long pay = SupermarketCheckoutTaskFirst.payCostTime.getAndSet(0);
                    long pack = SupermarketCheckoutTaskFirst.packCostTime.getAndSet(0);
                    System.out.println(String.format("实时统计各阶段耗时: price: %d, pay: %d, pack: %d", price/sumTimes, pay/sumTimes, pack/sumTimes));
                }
            }
        };
        taskExecutor.realTimeThread = thread;
        taskExecutor.start();
    }

}
